package com.qf.service.impl;

import com.qf.api.CacheFeign;
import com.qf.constant.CacheConstants;
import com.qf.constant.StrategyConstants;
import com.qf.model.StandardSubmit;
import com.qf.service.StrategyService;
import com.qf.util.PushMsgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Set;

/**
 * 5分钟内的限流策略
 *
 * @Author ztf
 * @Date 19:45 2021/11/24
 **/
@Service(value = "limitFiveMinutes")
@Slf4j
public class LimitFiveMinutesServiceImpl implements StrategyService {
    @Autowired
    private CacheFeign cacheFeign;

    @Autowired
    private PushMsgUtil pushMsgUtil;


    /**
     * 策略方法
     * 限流策略
     *
     * @param standardSubmit
     * @return
     */
    @Override
    public boolean execute(StandardSubmit standardSubmit) {
        log.info("【策略模块-限流策略】5分钟内的限流策略开始执行！！！");

        //1. 获取客户id和目标手机号
        //创建key id+目标手机号
        String key = CacheConstants.CACHE_PREFIX_SMS_LIMIT + standardSubmit.getClientID() + ":" + standardSubmit.getDestMobile();

        //2. 获取当前短信的发送时间毫秒值，和五分钟之前的毫秒值
        Long sendTime = standardSubmit.getSendTime().getTime();
        Long fiveMinutesAgo =sendTime - 1000*60*5;

        //3. 查询五分钟内客户发送过几条短信
        Set<String> value = cacheFeign.zRangeByScore(key, fiveMinutesAgo, sendTime);

        //4. 判断发送条数
        if (value != null && value.size() >= 3) {
            log.info("【策略模块-限流策略】5分钟内的短信发送条数超过上限，发送失败，已发送条数={}", value.size());
            pushMsgUtil.sendLog(standardSubmit, StrategyConstants.STRATEGY_ERROR_LIMIT);
            pushMsgUtil.pushReport(standardSubmit, StrategyConstants.STRATEGY_ERROR_LIMIT);
            return false;
        } else {
            log.info("【策略模块-限流策略】发送成功，已发送条数={}", value.size());
            return true;
        }
    }
}
